package com.example.controller;

import com.example.domain.po.Keyword;
import com.example.service.KeywordService;
import com.example.util.PageBean;
import com.example.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/keyword")
public class KeywordController {

    @Autowired
    private  KeywordService keywordService;

    @Value("${file.path}")
    private String path;
    @PostMapping("/add")
    public Result<String> add( Keyword keyword) throws IOException {

        if (keyword.getFile()!=null) {
            var oldFilename = keyword.getFile().getOriginalFilename();


            int i = oldFilename.lastIndexOf(".");
            var suffix = oldFilename.substring(i);
            var newFilename = String.valueOf(UUID.randomUUID()) + suffix;
            var file = new File(path, newFilename);
            keyword.getFile().transferTo(file);
            keyword.setPhotopath(newFilename);
        }
            keywordService.add(keyword);
            return Result.success("添加成功");

    }

    @GetMapping("/list")
    public Result<PageBean<Keyword>> list(Integer pageNum,
                                           Integer pageSize,
                                           String name
    ) {
        return Result.success(keywordService.list(pageNum, pageSize, name));
    }


    /**
     * 获取关键词的名称和id
     * @return
     */
    @GetMapping("/getNameAndId")
    public Result<List<Map<String,Object>>> getNameAndId(){
        return Result.success(keywordService.getNameAndId());
    }

    /**
     * 通过id获取详情
     * @param id
     * @return
     */
    @GetMapping("/getById")
    public Result<Keyword> getById(Integer id){
        return Result.success(keywordService.getById(id));
    }

}
